import http from '@/plugins/axios'
import Axios from '@/plugins/axios/Axios'

export interface CourseListType<T> {
  data: T[]
  lastPage: number
  page: number
  total: number
}

export default class CrudApi<T> {
  private http: Axios = http

  constructor(private url: string) {
    this.url = url
  }

  getResourceApi(pageOption?: crudTable.PageOption) {
    const sort = {[pageOption?.sort?.prop as string]: pageOption?.sort?.order}
    let where
    if (pageOption?.search?.value) {
      where = {[pageOption?.search?.prop!]: {$regex: pageOption?.search?.value}}
    }
    const query = pageOption
        ? `?query=${JSON.stringify({
          where,
          limit: pageOption.pageSize,
          page: pageOption.currentPage,
          sort,
          populate: pageOption.populate ?? ''
        })}`
        : ''
    return this.http.request<CourseListType<T>>({
      url: `${this.url}${query}`,
    })
  }

  getResourceApiById(id: string) {
    return this.http.request<T>({
      url: `${this.url}/${id}`,
    })
  }

  updateResourceApiById(id: string, data: T) {
    return this.http.request<T>({
      url: `${this.url}/${id}`,
      method: 'PUT',
      data,
    })
  }

  createResourceApi(data: T) {
    return this.http.request<T>({
      url: `${this.url}`,
      method: 'POST',
      data,
    })
  }

  removeResourceApi(id: string) {
    return this.http.request<T>({
      url: `${this.url}/${id}`,
      method: 'DELETE',
    })
  }

  getOptions() {
    return this.http.request<crudTable.OptionsType>({
      url: `${this.url}/options`,
    })
  }
}
